<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="关键字" prop="keywords">
          <el-input
            v-model="queryParams.keywords"
            placeholder="行政区划名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="mb-10px">
        <el-button
          v-hasPerm="['sys:region:add']"
          type="success"
          icon="plus"
          @click="handleOpenDialog('0')"
        >
          新增
        </el-button>
      </div>
      <div>
        <el-button v-hasPerm="'sys:user:import'" icon="upload" @click="handleOpenImportDialog">
          导入
        </el-button>

        <el-button v-hasPerm="'sys:user:export'" icon="download" @click="handleExport">
          导出
        </el-button>
      </div>

      <el-table
        v-loading="loading"
        :data="pageData"
      >
        <el-table-column label="行政区划名称" min-width="300">
          <template #default="scope">
            <template v-if="scope.row.icon && scope.row.icon.startsWith('el-icon')">
              <el-icon style="vertical-align: -0.15em">
                <component :is="scope.row.icon.replace('el-icon-', '')" />
              </el-icon>
            </template>
            <template v-else-if="scope.row.icon">
              <div :class="`i-svg:${scope.row.icon}`" />
            </template>
            {{ scope.row.name }}
          </template>
        </el-table-column>

        <el-table-column label="level" align="center" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.level === RegionTypeEnum.PROVINCE" type="success" effect="dark">
              省
            </el-tag>
            <el-tag v-if="scope.row.level === RegionTypeEnum.CITY" type="success" effect="dark">
              市
            </el-tag>
            <el-tag v-if="scope.row.level === RegionTypeEnum.DISTRICT" type="success" effect="dark">
              区县
            </el-tag>
            <el-tag v-if="scope.row.level === RegionTypeEnum.TOWN" type="success" effect="dark">
              乡镇或街道
            </el-tag>
            <el-tag v-if="scope.row.level === RegionTypeEnum.VILLAGE" type="success" effect="dark">
              村或居委会
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="区域编码" align="left" width="150" prop="areaCode" />
        <el-table-column label="父区域编码" align="left" width="150" prop="parentAreaCode" />
        <el-table-column label="简称" align="left" width="100" prop="shortname" />
        <el-table-column label="全称" align="left" width="200" prop="mergerName" />
        <el-table-column label="首字母" align="center" width="50" prop="first" />
        <el-table-column label="经度" align="center" width="100" prop="lng" />
        <el-table-column label="纬度" align="center" width="100" prop="lng" />
        <el-table-column label="pinyin" align="left" width="100" prop="pinyin" />
        <el-table-column label="code" align="center" width="100" prop="code" />
        <el-table-column label="zipCode" align="center" width="100" prop="zipCode" />
        <el-table-column fixed="right" align="center" label="操作" width="220">
          <template #default="scope">
            <el-button
              v-if="scope.row.level < 5"
              v-hasPerm="['sys:region:add']"
              type="primary"
              link
              size="small"
              icon="plus"
              @click.stop="handleOpenDialog(scope.row.areaCode)"
            >
              新增
            </el-button>

            <el-button
              v-hasPerm="['sys:region:edit']"
              type="primary"
              link
              size="small"
              icon="edit"
              @click.stop="handleOpenDialog(undefined, scope.row.id)"
            >
              编辑
            </el-button>
            <el-button
              v-hasPerm="['sys:region:delete']"
              type="danger"
              link
              size="small"
              icon="delete"
              @click.stop="handleDelete(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>

    <el-drawer
      v-model="dialog.visible"
      :title="dialog.title"
      :size="drawerSize"
      @close="handleCloseDialog"
    >
      <el-form ref="regionFormRef" :model="formData" :rules="rules" label-width="150px">
        <el-form-item label="父级行政区划" prop="parentAreaCode">
          <el-tree-select
            v-model="formData.parentAreaCode"
            placeholder="选择上级行政区划"
            :data="regionOptions"
            filterable
            check-strictly
            :render-after-expand="false"
            @change="handSelectLevel"
          />
        </el-form-item>
        <el-form-item label="行政区划名称" prop="name" label-width="150px">
          <el-input v-model="formData.name" placeholder="请输入行政区划名称" />
        </el-form-item>
        <el-form-item label="行政区划区域编码" prop="areaCode">
          <el-input v-model="formData.areaCode" placeholder="请输入行政区划区域编码" />
        </el-form-item>
        <el-form-item label="行政区划父区域编码" prop="parentAreaCode">
          <el-input v-model="formData.parentAreaCode" placeholder="请输入行政区划父区域编码" />
        </el-form-item>
        <el-form-item label="行政区划简称" prop="shortname">
          <el-input v-model="formData.shortname" placeholder="请输入行政区划简称" />
        </el-form-item>

        <el-form-item label="行政区划全称" prop="mergerName">
          <el-input v-model="formData.mergerName" disabled placeholder="请输入行政区划全称" />
        </el-form-item>

        <el-form-item label="行政区划类型" prop="level">
          <el-radio-group v-model="formData.level" @change="handleregionTypeChange">
            <el-radio disabled :value="RegionTypeEnum.PROVINCE">省</el-radio>
            <el-radio disabled :value="RegionTypeEnum.CITY">市</el-radio>
            <el-radio disabled :value="RegionTypeEnum.DISTRICT">区县</el-radio>
            <el-radio disabled :value="RegionTypeEnum.TOWN">乡镇或街道</el-radio>
            <el-radio disabled :value="RegionTypeEnum.VILLAGE">村或居委会</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="行政区划拼音" prop="pinyin">
          <el-input v-model="formData.pinyin" disabled placeholder="请输入行政区划拼音" />
        </el-form-item>

        <el-form-item label="行政区划长途区号" prop="code">
          <el-input v-model="formData.code" placeholder="请输入行政区划长途区号" />
        </el-form-item>

        <el-form-item label="行政区划邮编" prop="zipCode">
          <el-input v-model="formData.zipCode" placeholder="请输入行政区划邮编" />
        </el-form-item>

        <el-form-item label="行政区划首字符" prop="first">
          <el-input v-model="formData.first" disabled placeholder="请输入行政区划首字母" />
        </el-form-item>

        <el-form-item label="行政区划经度" prop="lng">
          <el-input v-model="formData.lng" placeholder="请输入行政区划经度" />
        </el-form-item>

        <el-form-item label="行政区划首纬度" prop="lat">
          <el-input v-model="formData.lat" placeholder="请输入行政区划纬度" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup>
import { useAppStore } from "@/store/modules/app.store";
import { DeviceEnum } from "@/enums/settings/device.enum";

import RegionAPI from "@/api/system/region.api";
import { RegionTypeEnum } from "@/enums/system/region.enum";
import { pinyin } from "pinyin-pro";
defineOptions({
  name: "Region",
  inheritAttrs: false,
});
const pageData = ref();
const total = ref(0);
const appStore = useAppStore();

const queryFormRef = ref();
const regionFormRef = ref();

const loading = ref(false);
const dialog = reactive({
  title: "新增行政区划",
  visible: false,
});

const drawerSize = computed(() => (appStore.device === DeviceEnum.DESKTOP ? "600px" : "90%"));
// 查询参数
const queryParams = reactive({});
// 行政区划表格数据
const regionTableData = ref([]);
// 顶级行政区划下拉选项
const regionOptions = ref([]);
// 初始行政区划表单数据
const initialregionFormData = ref({
  id: undefined,
  pid: "0",
  shortname: "",
  name: "",
  mergerName: "", // 默认行政区划
  level: 0,
  pinyin: "",
  code: "",
  zipCode: "",
  first: "",
  lng: "",
  lat: "",
  treePath: "",
  areaCode: null,
  parentAreaCode: 0,
});
// 行政区划表单数据
const formData = ref({ ...initialregionFormData.value });

watch(
  () => formData.value.name,
  (newName) => {
    handSelectLevel(formData.value.parentAreaCode);
    console.log(newName);
  }
);

watch(
  () => formData.value.shortname,
  (newName) => {
    formData.value.pinyin = formData.value.shortname
      ? pinyin(formData.value.shortname, {
          toneType: "none",
          type: "array",
        }).join("")
      : "";
    formData.value.first = formData.value.name
      ? pinyin(formData.value.name, {
          toneType: "none",
          type: "array",
        })
          .join(" ")
          .slice(" ")
          .at(0)
          .charAt(0)
          .toUpperCase()
      : " ";
    console.log(newName);
  }
);
// 表单验证规则
const rules = reactive({
  pid: [{ required: true, message: "请选择父级行政区划", trigger: "blur" }],
  name: [{ required: true, message: "请输入行政区划名称", trigger: "blur" }],
  level: [{ required: true, message: "请选择行政区划类型", trigger: "blur" }],
  shortname: [{ required: true, message: "请输入简称", trigger: "blur" }],
  mergerName: [{ required: true, message: "请输入全称", trigger: "blur" }],
  /*  lng: [{ required: true, message: "请输入经度", trigger: "blur" }],
  lat: [{ required: true, message: "请输入纬度", trigger: "change" }],*/
});

// 选择表格的行行政区划ID
const selectedregionId = ref();

// 查询行政区划
function handleQuery() {
  loading.value = true;
  RegionAPI.getList(queryParams)
    .then((data) => {
      regionTableData.value = data;
      pageData.value = data.records;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

function handSelectLevel(regionCode) {
  if (regionCode !== "0") {
    RegionAPI.getFormDataByCode(regionCode).then((data) => {
      formData.value.level = Number(data?.level ?? 0) + 1;
      formData.value.treePath = data?.treePath || "";
      RegionAPI.getMergerNameByTreePath(formData.value.treePath).then((data1) => {
        formData.value.mergerName = (data1 ?? "") + "," + formData.value.name;
      });
    });
  } else {
    formData.value.level = 1;
    formData.value.mergerName = "中国" + "," + formData.value.name;
  }
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  handleQuery();
}

// 行点击事件
function handleRowClick(row) {
  selectedregionId.value = row.id;
}

/**
 * 打开表单弹窗
 *
 * @param parentId 父行政区划ID
 * @param regionId 行政区划ID
 */
function handleOpenDialog(parentId, regionId) {
  RegionAPI.getOptions(true)
    .then((data) => {
      regionOptions.value = [{ value: "0", label: "中国", children: data }];
    })
    .then(() => {
      dialog.visible = true;
      if (regionId) {
        dialog.title = "编辑行政区划";
        RegionAPI.getFormData(regionId).then((data) => {
          initialregionFormData.value = { ...data };
          formData.value = data;
        });
      } else {
        dialog.title = "新增行政区划";
        formData.value.parentAreaCode = parentId?.toString();
        handSelectLevel(parentId);
      }
    });
}

// 行政区划类型切换
function handleregionTypeChange() {
  // 如果行政区划类型改变
  if (formData.value.type !== initialregionFormData.value.type) {
    if (formData.value.type === RegionTypeEnum.region) {
      // 目录切换到行政区划时，清空组件路径
      if (initialregionFormData.value.type === RegionTypeEnum.CATALOG) {
        formData.value.component = "";
      } else {
        // 其他情况，保留原有的组件路径
        formData.value.routePath = initialregionFormData.value.routePath;
        formData.value.component = initialregionFormData.value.component;
      }
    }
  }
}

/**
 * 提交表单
 */
function handleSubmit() {
  regionFormRef.value.validate((isValid) => {
    if (isValid) {
      const regionId = formData.value.id;
      if (regionId) {
        //修改时父级行政区划不能为当前行政区划
        if (formData.value.parentId == regionId) {
          ElMessage.error("父级行政区划不能为当前行政区划");
          return;
        }
        RegionAPI.update(regionId, formData.value).then(() => {
          ElMessage.success("修改成功");
          handleCloseDialog();
          handleQuery();
        });
      } else {
        RegionAPI.create(formData.value).then(() => {
          ElMessage.success("新增成功");
          handleCloseDialog();
          handleQuery();
        });
      }
    }
  });
}

// 删除行政区划
function handleDelete(regionId) {
  if (!regionId) {
    ElMessage.warning("请勾选删除项");
    return false;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      RegionAPI.deleteById(regionId)
        .then(() => {
          ElMessage.success("删除成功");
          handleQuery();
        })
        .finally(() => {
          loading.value = false;
        });
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

function resetForm() {
  regionFormRef.value.resetFields();
  regionFormRef.value.clearValidate();
  formData.value = {
    id: undefined,
    pid: "0",
    shortname: "",
    name: "",
    mergerName: "", // 默认行政区划
    level: RegionTypeEnum.PROVINCE, // 默认行政区划
    pinyin: "",
    code: "",
    zipCode: "",
    first: "",
    lng: "",
    lat: "",
    treePath: "",
    areaCode: null,
    parentAreaCode: 0,
  };
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  resetForm();
}

onMounted(() => {
  handleQuery();
});
</script>
